package com.atguigu.bookcity.service.impl;

import com.atguigu.bookcity.entity.Book;
import com.atguigu.bookcity.entity.Category;
import com.atguigu.bookcity.entity.vo.bookshow;
import com.atguigu.bookcity.exception.BookCityException;
import com.atguigu.bookcity.mapper.BookMapper;
import com.atguigu.bookcity.service.BookService;
import com.atguigu.bookcity.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zsc
 * @since 2021-03-20
 */
@Service
@Transactional
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    @Resource
    private CategoryService categoryService;


    @Override
    public String addbook(Book book) {
        baseMapper.insert(book);
        return book.getId();
    }

    @Override
    public List<bookshow> getAllBooks() {
        List<Book> bookList = list();
        List<bookshow> bookShows = new ArrayList<>();
        List<Category> categoryList = categoryService.list();
        bookList.forEach(book -> {
            bookshow bookshow = new bookshow();
            for (Category category : categoryList) {
                if (category.getId().equals(book.getFirstId())) {
                    bookshow.setFirstcategory(category.getTitle());
                    continue;
                }
                if (category.getId().equals(book.getSecondId())) {
                    bookshow.setSecondcategory(category.getTitle());
                }
            }
            BeanUtils.copyProperties(book, bookshow);
            bookShows.add(bookshow);
        });
        return bookShows;
    }

    @Override
    public bookshow getBookById(String bookId) {
        //如果Redis取不到数据就从数据库中查询
        bookshow bookshow;
        Book book = getById(bookId);
        if (book == null)
            throw new BookCityException(201, "没有此书");
        bookshow = new bookshow();
        BeanUtils.copyProperties(book, bookshow);
        Category firstCategory = categoryService.getById(book.getFirstId());
        Category secondCategory = categoryService.getById(book.getSecondId());
        bookshow.setFirstcategory(firstCategory.getTitle());
        bookshow.setSecondcategory(secondCategory.getTitle());
        return bookshow;
    }
}
